package cqrtplm.listener;

import cn.hutool.extra.spring.SpringUtil;
import com.hustcad.plm.pdm.workflow.annotion.CustomListener;
import com.hustcad.plm.pdm.workflow.annotion.CustomListenerField;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlowContainer;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService;
import cqrtplm.service.RTCreateEcaByEcnService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.impl.el.FixedValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigInteger;

@CustomListener(
        category = "润通",
        description = "基于ECN创建图纸修改ECA"
)
public class RTCreateEcaByEcnExtListener implements ExecutionListener {
    private static final Logger log = LoggerFactory.getLogger(RTCreateEcaByEcnExtListener.class);
    private static final long serialVersionUID = -1118383835323266817L;
    @CustomListenerField(
            description = "类型内部名称(等价于逻辑标识符)",
            defaultValue = "",
            required = true
    )
    private FixedValue typeName;

    public void notify(DelegateExecution delegateExecution) {
        try {
            log.info("开始执行监听 ==> 根据变更对象工作负责人分发ECA RTCreateEcaByEcnExtListener");
            String workFlowContainerId = delegateExecution.getProcessInstanceBusinessKey();
            if (StringUtils.isBlank(workFlowContainerId)) {
                workFlowContainerId = delegateExecution.getVariable("workFlowContainerId").toString();
            }

            TyplmWorkFlowContainerService typlmWorkFlowContainerService = (TyplmWorkFlowContainerService) SpringUtil.getBean(
                    TyplmWorkFlowContainerService.class);
            WorkFlowContainer workFlowContainer = (WorkFlowContainer) typlmWorkFlowContainerService.selectOneByOid(
                    new BigInteger(workFlowContainerId));
            RTCreateEcaByEcnService rtCreateEcaByEcnService = (RTCreateEcaByEcnService) SpringUtil.getBean(
                    RTCreateEcaByEcnService.class);
            rtCreateEcaByEcnService.createEcaByEcnExt(workFlowContainer.getBaseObjectOid(), ObjectUtils.isEmpty(
                    this.typeName) ? null : this.typeName.getExpressionText());
            log.info("正常执行监听结束 <== 根据变更对象工作负责人分发ECA RTCreateEcaByEcnExtListener");
        } catch (Exception e) {
            log.error("监听RTCreateEcaByEcnExtListener异常：", e);
            throw e;
        }
    }
}
